<template>
  <div style="height: 100%; width: 100%">
    <!-- 查询框 -->
    <div>
      <el-select v-model="searchType" placeholder="请选择查询条件" style="width: 150px;">
        <el-option label="序号" value="id"></el-option>
        <el-option label="患者姓名" value="name"></el-option>
      </el-select>
      <el-input v-model="keyword" style="width: 300px; margin-left: 10px; margin-right: 10px" placeholder="请输入关键词"></el-input>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
    </div>

    <!-- 操作框 -->
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="showAddDialog">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>

    <!-- 表格 -->
    <div>
      <el-table :data="appointments" stripe :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="id" label="序号" width="70" align="center"></el-table-column>
        <el-table-column prop="patient_name" label="患者姓名"></el-table-column>
        <el-table-column prop="appointment_date" label="预约日期"></el-table-column>
        <el-table-column prop="appointment_time" label="预约时间"></el-table-column>
        <el-table-column prop="doctor_name" label="医生姓名"></el-table-column>
        <el-table-column prop="appointment_purpose" label="预约目的"></el-table-column>
        <el-table-column prop="status" label="状态"></el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div style="margin-top: 20px; text-align: center;">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalItems">
      </el-pagination>

      <!-- 新增/编辑弹窗 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
        <el-form ref="form" :model="editItem" label-width="80px">
          <el-form-item label="患者姓名" prop="patient_name">
            <el-input v-model="editItem.patient_name"></el-input>
          </el-form-item>
          <el-form-item label="预约日期" prop="appointment_date">
            <el-date-picker v-model="editItem.appointment_date" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
<!--          <el-form-item label="预约日期" prop="appointment_date">-->
<!--            <el-input v-model="editItem.appointment_date"></el-input>-->
<!--          </el-form-item>-->
          <el-form-item label="预约时间" prop="appointment_time">
            <el-time-picker v-model="editItem.appointment_time" type="time" placeholder="选择时间" value-format="HH:mm:ss"></el-time-picker>
          </el-form-item>
<!--          <el-form-item label="预约时间" prop="appointment_time">-->
<!--            <el-input v-model="editItem.appointment_time"></el-input>-->
<!--          </el-form-item>-->
          <el-form-item label="医生姓名" prop="doctor_name">
            <el-input v-model="editItem.doctor_name"></el-input>
          </el-form-item>
          <el-form-item label="预约目的" prop="appointment_purpose">
            <el-input v-model="editItem.appointment_purpose"></el-input>
          </el-form-item>
<!--          <el-form-item label="状态" prop="status">-->
<!--            <el-input v-model="editItem.status"></el-input>-->
<!--          </el-form-item>-->
          <el-form-item label="状态" prop="status">
            <el-select v-model="editItem.status" placeholder="请选择状态">
              <el-option label="待治疗" value="待治疗"></el-option>
              <el-option label="已治疗" value="已治疗"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="handleSaveEdit">{{ isEditing ? '保存' : '新增' }}</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'InventoryView2',
  data() {
    return {
      appointments: [], // 确保初始化为空数组
      selectedRows: [], // 存储选中的行的 ID
      currentPage: 1, // 当前页数
      pageSize: 5, // 每页显示的条数
      totalItems: 0, // 总条数
      searchType: 'id', // 默认查询类型
      keyword: '', // 查询关键词
      dialogVisible: false, // 新增/编辑弹窗可见性
      editItem: { // 编辑/新增的数据
        patient_name: '',
        appointment_date: '',
        appointment_time: '',
        doctor_name: '',
        appointment_purpose: '',
        status: ''
      },
      isEditing: false // 是否处于编辑状态 // 设置编辑状态为false表示新增,true表示编辑
    };
  },
  computed: {
    dialogTitle() {
      return this.isEditing ? '编辑信息' : '新增信息'; //false为新增，true为编辑
    }
  },
  mounted() {
    this.search();
  },
  methods: {
    search() {
      let url = 'http://localhost:8080/appointments/selectAll';
      let params = {
        page: this.currentPage,
        size: this.pageSize
      };

      if (this.keyword) {
        // 如果输入了关键词，则根据选择的查询条件发送相应的请求
        // 构建带查询参数的URL
        // console.log(this.keyword);
        url = `http://localhost:8080/appointments/selectBy${this.searchType}?${this.searchType}=${this.keyword}`;
      }

      axios.get(url, { params })
          .then(response => {
            // console.log('后端返回的数据:', response.data);
            const data = response.data.data;
            this.appointments = data.list;
            this.totalItems = data.total;
          })
          .catch(error => {
            console.error('Error fetching inventory:', error);
          });
    },
    reset() {//重置
      this.searchType = 'id';
      this.keyword = '';
      this.currentPage = 1;
      this.pageSize = 5;
      this.search();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.search();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.search();
    },
    handleSelectionChange(val) {//选择的行
      this.selectedRows = val.map(row => row.id);
    },
    showAddDialog() {
      this.isEditing = false;
      this.editItem = { // 新增表单置空
        patient_name: '',
        appointment_date: '',
        appointment_time: '',
        doctor_name: '',
        appointment_purpose: '',
        status: ''
      };
      this.dialogVisible = true;
    },
    closeDialog() {
      this.dialogVisible = false;
      this.isEditing = false;
    },
    handleAdd() {
      // 实现新增功能的逻辑
      axios.post("http://localhost:8080/appointments/add", this.editItem)
          .then(response => {
            // 处理新增成功逻辑
            this.$message.success("新增成功");
            this.dialogVisible = false;
            this.search(); // 刷新数据
          })
          .catch(error => {
            // 处理新增失败逻辑
            console.error('Error adding new item:', error);
            this.$message.error("新增失败");
          });
    },
    handleEdit(row) {
      // 将选中行的数据赋值给编辑的数据项
      this.editItem = Object.assign({}, row);
      // 设置编辑状态为true
      this.isEditing = true; // 设置编辑状态为true，表示编辑
      // 打开新增/编辑弹窗
      this.dialogVisible = true;
    },
    handleSaveEdit() {
      // 发送编辑/新增请求到后端
      if (this.isEditing) {
        // 编辑状态下发送编辑请求
        axios.put("http://localhost:8080/appointments/edit", this.editItem)
            .then(response => {
              // 处理编辑成功逻辑
              this.$message.success("编辑成功");
              this.closeDialog();
              this.search(); // 刷新数据
            })
            .catch(error => {
              // 处理编辑失败逻辑
              console.error('Error editing item:', error);
              this.$message.error("编辑失败");
            });
      } else {
        // 新增状态下发送新增请求
        this.handleAdd();
      }
    },
    handleDelete(id) {
      this.$confirm('此操作将永久删除该条目，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:8080/appointments/delete/${id}`)
            .then(response => {
              this.$message.success('删除成功');
              this.search(); // 刷新数据
            })
            .catch(error => {
              console.error('Error deleting item:', error);
              this.$message.error('删除失败');
            });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    delBatch() {
      // 确认是否删除选中的行
      this.$confirm('此操作将永久删除所选条目，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 批量删除操作
        axios.delete(`http://localhost:8080/appointments/deleteBatch`, {  data: this.selectedRows })
            .then(response => {
              this.$message.success('批量删除成功');
              this.search(); // 刷新数据
              this.selectedRows = []; // 清空选中的行
            })
            .catch(error => {
              console.error('Error deleting batch:', error);
              this.$message.error('批量删除失败');
            });
      }).catch(() => {
        this.$message.info('已取消批量删除');
      });
    }
  }
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
